<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="24">
          <el-col :span="6" :xs="24">
            <el-form-item label="APP名称">
              <el-input v-model="page.appName"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="状态">
              <el-select style="width: 100%" v-model="page.status" clearable>
                <el-option label="启用" :value="1"></el-option>
                <el-option label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="text-align: right;margin-bottom: 10px">
      <el-button type="primary" @click="visible ={ isShow:true,type:'add',title:'添加'}">添加</el-button>
    </div>
    <Table :tableColumn="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #status="{row}">
        <el-switch :model-value="row.status === 1" @change="changeStatus(row)"></el-switch>
      </template>
      <template #handle="{row}">
        <el-button type="text" @click="productInfoVisible = true,tableRows = {...row}" v-permiss="['product-config']">
          关于我们配置
        </el-button>
        <el-button type="text" @click="resourcesConfig(row)">资源配置</el-button>
        <el-button type="text" @click="setProductShowConfig(row)">产品展示配置</el-button>
        <el-button type="text" @click="comprehensiveSet(row)">综合设置</el-button>
        <el-button type="text" @click="updateList(row)">编辑</el-button>
        <el-button type="text" @click="threePartyConfig(row)">三方服务配置</el-button>
      </template>
    </Table>
    <!--    关于我们配置-->
    <Dialog v-model="productInfoVisible" @cancel="productInfoVisible = false"
            :title="tableRows.appName  + ' - ' + '关于我们配置'"
            @close="tableRows = {}"
            @confirm="productInfoConfirm"
    >
      <el-form label-width="80px">
        <el-form-item label="联系电话">
          <el-input v-model="tableRows.phone"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="tableRows.email"/>
        </el-form-item>
        <el-form-item label="whatsApp">
          <el-input v-model="tableRows.appContact"/>
        </el-form-item>
        <el-form-item label="关于我们">
          <el-input type="textarea" v-model="tableRows.remark" :rows="5"/>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    资源配置-->
    <Dialog v-model="resourcesVisible"
            :footer="$permiss(['resources-update'])"
            @cancel="resourcesVisible = false" :title="tableRows.appName  + ' - ' +  '资源配置'"
            @confirm="resourcesConfirm"
    >
      <el-tree
          ref="treeRef"
          :data="resourcesData"
          show-checkbox
          node-key="key"
          :props="{label:'name'}"
      ></el-tree>
    </Dialog>
    <!--     综合设置-->
    <Dialog v-model="configSet.isShow"
            @cancel="configSet.isShow = false" :title="configSet.title"
            @confirm="configSetConfirm"
            width="55%"
    >
      <el-card shadow="never" style="margin-bottom: 10px">
        <template #header>
          服务项设置
        </template>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-switch active-text="OCR" v-model="configSet.rows.ocrStatus" :active-value="1"
                       @change="changeStatusSwitch('ocrStatus')"
                       :inactive-value="0"></el-switch>
          </el-col>
          <el-col :span="6">
            <el-switch active-text="人脸比对" v-model="configSet.rows.faceStatus" @change="changeStatusSwitch('faceStatus')"
                       :active-value="1"
                       :inactive-value="0"></el-switch>
          </el-col>
          <el-col :span="6">
            <el-switch active-text="活体校验" v-model="configSet.rows.livingStatus" :active-value="1"
                       @change="changeStatusSwitch('livingStatus')"
                       :inactive-value="0"></el-switch>
          </el-col>
          <el-col :span="6">
            <el-switch active-text="税卡校验" v-model="configSet.rows.rfcStatus" :active-value="1"
                       :inactive-value="0"></el-switch>
          </el-col>
        </el-row>

      </el-card>
      <el-card shadow="never" style="margin-bottom: 10px">
        <template #header>
          运营商认证设置
        </template>
        运营商认证成功后，
        <el-input style="width:120px" v-model="configSet.rows.validDay"/>
        天内无需重复认证
      </el-card>
      <el-card shadow="never" style="margin-bottom: 10px">
        <template #header>
          进件设置
        </template>
        订单结清时间在
        <el-input style="width:120px" v-model="configSet.rows.settleStart"/>
        -
        <el-input style="width:120px" v-model="configSet.rows.settleEnd"/>
        内，可自动生成复借订单
        <a-alert type="info" message="输入框中可输入负数代表提前，0表示当天，正数表示逾期"></a-alert>
      </el-card>
    </Dialog>

    <Dialog v-model="visible.isShow"
            @cancel="visible.isShow = false" :title="visible.title"
            @confirm="upDateConfirm"
            @close="clearForm"
            width="55%">
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="APP名称" prop="appName" :rules="[
             {required: true, message: '不能为空', trigger: 'blur'}
        ]">
          <el-input v-model="form.appName"/>
        </el-form-item>
        <el-form-item label="OCR识别">
          <el-input v-model="form.ocrFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item label="人脸对比">
          <el-input v-model="form.faceFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item label="活体检测">
          <el-input v-model="form.livingBodyFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item label="短信验证码">
          <el-input v-model="form.smsCodeFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
        <el-form-item label="语音验证码">
          <el-input v-model="form.voiceFee" oninput="value = value.replace(/[^\d.]/g, '')"/>
        </el-form-item>
      </el-form>
    </Dialog>

    <!-- 第三方服务配置 -->
    <Dialog v-model="visibleThreeConfig"
            @cancel="visibleThreeConfig= false" title="第三方服务配置"
            @confirm="threeConfigConfirm"
            width="55%">
      <div>
        <h4 style="padding: 10px 0;border-bottom: 1px solid #eeeeee;margin: 0">短信</h4>
        <div style="margin-top:10px">
          <span style="margin-right: 10px">验证码短信</span>
          <el-radio-group v-model="codeSms.id">
            <template v-for="item in smsConfig">
              <el-radio v-if="item.type === 1" :key="item.id" :label="item.id">
                {{ item.smsName }}
              </el-radio>
            </template>
          </el-radio-group>
        </div>
        <div style="margin-top:10px">
          <span style="margin-right: 10px">语音验证码</span>
          <el-radio-group v-model="voiceSMS.id">
            <template v-for="item in smsConfig">
              <el-radio v-if="item.type === 4" :key="item.id" :label="item.id">
                {{ item.smsName }}
              </el-radio>
            </template>
          </el-radio-group>
        </div>

      </div>

    </Dialog>

    <!-- 产品展示配置 -->
    <Dialog v-model="productShowVisible"
            @cancel="productShowVisible= false" :title="tableRows.appName + '-' +  '产品展示配置'"
            @confirm="productShowConfirm"
            width="55%">
      <el-button type="primary" icon="plus" style="margin-bottom: 15px">新增</el-button>
      <el-form :inline="true" style="margin-bottom: 15px" v-for="(item,index) in productShowConfig" :key="index">
        <el-row :gutter="24">
          <el-col :span="14" :xs="24">
            <el-form-item label="客户在APP内累计结清次数" label-width="200px">
              <el-input style="width:120px;" v-model="item.settleStart"></el-input>
              -
              <el-input style="width:120px;" v-model="item.settleEnd"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" :xs="24">
            <el-form-item label="指定展示产品">
              <el-select style="width: 200px" multiple v-model="item.productNameList">
                <el-option v-for="item in configProductList" :key="item.productName" :value="item.productName"
                           :label="item.productName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {nextTick, onMounted, reactive, ref, toRefs} from 'vue'
import {
  fetchLoanAppList,
  updateLoanConfig,
  fetchResources,
  updateResources,
  fetchSetConfig,
  updateSetCofig,
  addProduct,
  fetchSmsConfig,
  updateConfigSms,
  fetchProductConfig,
  fetchProductShowList,
  addProductShowConfig
} from "@/api/loanSupermarket";
import {ElMessage, ElMessageBox} from "element-plus";
import {updateFeedback} from "../../../api/user";
import deepcopy from "deepcopy";

const tableColumn = [
  {label: 'APP名称', prop: 'appName', align: 'center'},
  {label: '创建时间', prop: 'createTime', align: 'center'},
  {label: 'OCR识别', prop: 'ocrFee', align: 'center'},
  {label: '人脸对比', prop: 'faceFee', align: 'center'},
  {label: '活体检测', prop: 'livingBodyFee', align: 'center'},
  {label: '短信验证码', prop: 'smsCodeFee', align: 'center'},
  {label: '语音验证码', prop: 'voiceFee', align: 'center'},
  {label: '状态', prop: 'status', slot: 'status', align: 'center'},
  {label: '操作', slot: 'handle', align: 'center'},
]
export default {
  name: "LoanSupermarketList",
  setup() {
    const treeRef = ref(null)
    const formRef = ref(null)
    const state = reactive({
      tableData: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      productInfoVisible: false,
      resourcesVisible: false,
      productShowVisible: false,
      tableRows: {},
      productInfo: {},
      configProductList: [],
      productShowConfig: [],
      resourcesData: [],
      configSet: {
        isShow: false,
        title: '综合设置',
        rows: {}
      },
      visible: {
        isShow: false,
        title: '',
        type: '',
      },
      form: {
        appName: null,
        ocrFee: null,
        faceFee: null,
        livingBodyFee: null,
        smsCodeFee: null,
        voiceFee: null,
      },
      visibleThreeConfig: false,
      smsConfig: [],
      codeSms: {
        id: null
      },
      voiceSMS: {
        id: null
      }
    })

    async function getTableData() {
      const res = await fetchLoanAppList(state.page)
      if (res.code === 200) {
        const {list, total} = res.data
        state.tableData = list
        state.page.total = total
      }
    }

    function resetSearch() {
      state.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      getTableData()
    }

    function changeStatus({appId, status}) {
      ElMessageBox.confirm('确认进行此操作?', '提示', {
        type: 'warning',
      }).then(async () => {
        const res = await updateLoanConfig({
          appId, status: status === 1 ? 0 : 1
        })
        if (res.code === 200) {
          ElMessage.success('操作成功')
          getTableData()
        }
      }).catch(() => {

      });
    }

    function formatResouresData(data) {
      return data.filter(item => {
        const children = data.filter(child => child.pid === item.id)
        children.length > 0 ? item.children = children : null
        return item.pid === 0
      })
    }

    async function resourcesConfig(row) {
      const res = await fetchResources({
        appId: row.appId
      })
      if (res.code === 200) {
        state.resourcesData = formatResouresData(res.data)
        state.resourcesVisible = true
        state.tableRows = {...row}
        nextTick(() => {
          const keys = res.data.filter(item => item.checked).sort((a, b) => a.id - b.id)
          keys.forEach(item => {
            treeRef.value.setChecked(item.key, true)
          })
        })
      }
    }

    async function productInfoConfirm() {
      const {appId, phone, email, remark, appContact} = state.tableRows
      const res = await updateLoanConfig({
        phone, email, remark, appId, appContact
      })
      if (res.code === 200) {
        state.productInfoVisible = false
        ElMessage.success('操作成功')
        getTableData()
      }
    }

    async function resourcesConfirm() {
      const treeKeys = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
      const res = await updateResources({
        appId: state.tableRows.appId,
        keyList: treeKeys
      })
      if (res.code === 200) {
        ElMessage.success('操作成功')
        state.resourcesVisible = false
        getTableData()
      }
    }

    function changeStatusSwitch(value) {
      const {ocrStatus, faceStatus, livingStatus} = state.configSet.rows
      if (value === 'faceStatus') {
        if (faceStatus === 1) {
          state.configSet.rows.ocrStatus = 1
          state.configSet.rows.livingStatus = 1
        }
      }
      if (value === 'ocrStatus' || value === 'livingStatus') {
        if ((ocrStatus === 1 || livingStatus === 1) && faceStatus === 1) {
          state.configSet.rows.ocrStatus = 1
          state.configSet.rows.livingStatus = 1
          return ElMessage.error('开启人脸对比时，需同时打开OCR和活体验证')
        }
      }
    }

    function updateList(row) {
      state.visible = {
        isShow: true,
        title: '编辑',
        type: 'update',
      }
      state.form = {
        appName: row.appName,
        ocrFee: row.ocrFee,
        faceFee: row.faceFee,
        livingBodyFee: row.livingBodyFee,
        smsCodeFee: row.smsCodeFee,
        voiceFee: row.voiceFee,
        ...row
      }
    }

    async function comprehensiveSet({appId, appName}) {
      const res = await fetchSetConfig({
        appId
      })
      if (res.code === 200) {
        state.configSet.isShow = true
        state.configSet.title = appName + ' - ' + '综合设置'
        state.configSet.rows = res.data
      }
    }

    // 获取产品展示配置
    async function setProductShowConfig(rows) {
      state.tableRows = {...rows}
      const res = await fetchProductConfig({
        appId: rows.appId
      })
      if (res.code === 200) {
        fetchProductShowList({appId: rows.appId}).then(res => {
          state.configProductList = res.data
        })
        state.productShowVisible = true
        if (res.data.length > 0) {
          state.productShowConfig = res.data.map(item => {
            item.productNameList = item.productIdList.map(item => item.productName)
            return item
          })
          console.log(state.productShowConfig)
        } else {
          state.productShowConfig.push({
            productNameList: [],
            settleStart: '',
            settleEnd: '',
          })
        }
      }
    }

    // 产品展示配置提交
    async function productShowConfirm() {
      const list = deepcopy(state.productShowConfig).map(item => {
        item.productList = state.configProductList.filter(v => {
          return item.productNameList.indexOf(v.productName) !== -1
        }).map(j => j.productId).join('*')
        delete item.productNameList
        delete item.productIdList
        return item
      })
      console.log(list)
      const res = await addProductShowConfig(list)
      if (res.code === 200) {
        state.productShowConfig = []
        state.productShowVisible = false
        ElMessage.success('操作成功')
        getTableData()
      }
    }

    async function configSetConfirm() {
      const res = await updateSetCofig({
        ...state.configSet.rows,
        settleStart: parseInt(state.configSet.rows.settleStart) || '',
        settleEnd: parseInt(state.configSet.rows.settleEnd) || '',
      })
      if (res.code === 200) {
        state.configSet.isShow = false
        ElMessage.success('操作成功')
        getTableData()
      }
    }

    function upDateConfirm() {
      formRef.value.validate(async (v) => {
        if (v) {
          const isAdd = state.visible.type === 'add'
          const params = {
            ...state.form,
            appName: state.form.appName,
            ocrFee: parseFloat(state.form.ocrFee),
            faceFee: parseFloat(state.form.faceFee),
            livingBodyFee: parseFloat(state.form.livingBodyFee),
            smsCodeFee: parseFloat(state.form.smsCodeFee),
            voiceFee: parseFloat(state.form.voiceFee),
          }
          const api = (params) => isAdd ? addProduct(params) : updateLoanConfig(params)
          const res = await api(params)
          if (res.code === 200) {
            ElMessage.success(isAdd ? '添加成功' : '编辑成功')
            state.visible.isShow = false
            getTableData()
          }
        }
      })
    }

    async function threePartyConfig({appId}) {
      const res = await fetchSmsConfig({appId})
      if (res.code === 200) {
        state.smsConfig = res.data
        state.codeSms.id = state.smsConfig.find(item => item.type === 1 && item.status === 1).id || {}
        state.voiceSMS.id = state.smsConfig.find(item => item.type === 4 && item.status === 1).id || {}
        state.visibleThreeConfig = true
      }
    }

    async function threeConfigConfirm() {
      const smsConfig = state.smsConfig.map(item => {
        if (item.type === 1) {
          if (state.codeSms.id === item.id) {
            item.status = 1
          } else {
            item.status = 0
          }
        }
        if (item.type === 4) {
          if (state.voiceSMS.id === item.id) {
            item.status = 1
          } else {
            item.status = 0
          }
        }
        return item
      })
      const params = [...smsConfig]
      console.log(params)
      const res = await updateConfigSms(params)
      if (res.code === 200) {
        ElMessage.success('操作成功')
        state.visibleThreeConfig = false
        getTableData()
      }
    }

    function codeSmsChange(value) {
      state.codeSms.id = value
      console.log(state.codeSms.id)
    }

    function clearForm() {
      formRef.value.resetFields()
      state.form = {
        appName: null,
        ocrFee: null,
        faceFee: null,
        livingBodyFee: null,
        smsCodeFee: null,
        voiceFee: null,
      }
    }

    onMounted(() => {
      getTableData()
    })
    return {
      treeRef,
      formRef,
      ...toRefs(state),
      tableColumn,
      changeStatus,
      getTableData,
      resetSearch,
      productShowConfirm,
      productInfoConfirm,
      resourcesConfirm,
      resourcesConfig,
      comprehensiveSet,
      setProductShowConfig,
      configSetConfirm,
      changeStatusSwitch,
      upDateConfirm,
      updateList,
      clearForm,
      threePartyConfig,
      threeConfigConfirm,
      codeSmsChange,
    }
  }
}
</script>

<style scoped>

</style>
